# $ANTLR 3.1.3 Mar 17, 2009 19:23:44 regexs.g 2011-12-07 15:51:40

import sys
from antlr3 import *
from antlr3.compat import set, frozenset
                
import sys
from DeterministicAutomata import *
from Determinizer import *
from AutomataBuilder import *



# for convenience in actions
HIDDEN = BaseRecognizer.HIDDEN

# token types
CARACTER=4
OP=6
T__10=10
DOT=5
EOF=-1
T__9=9
T__8=8
T__7=7

# token names
tokenNames = [
    "<invalid>", "<EOR>", "<DOWN>", "<UP>", 
    "CARACTER", "DOT", "OP", "'\\n'", "'('", "')'", "'|'"
]




class regexsParser(Parser):
    grammarFileName = "regexs.g"
    antlr_version = version_str_to_tuple("3.1.3 Mar 17, 2009 19:23:44")
    antlr_version_str = "3.1.3 Mar 17, 2009 19:23:44"
    tokenNames = tokenNames

    def __init__(self, input, state=None, *args, **kwargs):
        if state is None:
            state = RecognizerSharedState()

        super(regexsParser, self).__init__(input, state, *args, **kwargs)



        self.idaut = 1; self.abortar = False; self.automata = None



                


        

              
    def getErrorMessage(self, ruleName, ruleIndex):
        sys.stderr.write('Error al parsear la regex - '+ str(ruleName)+' - ' + str(ruleIndex) + '\n')
        sys.exit(1)
        self.abortar = True

    def getTokenErrorDisplay(t):
        sys.stderr.write('Error al parsear la regex - Token - '+ str(t) + '\n')
       
    def EarlyExitException(self, d, i):
        sys.stderr.write('Error al parsear la regex - exception - '+ str(d) + ' - '+ str(i) + '\n')
     
    def procesar_archivo(self):
        if self.abortar:
            print "abortando"
            sys.exit(1)

        if len(sys.argv)==1:
            print "REGEX ACEPTADA"
            print "Solo aceptando la entrada. Para correr todo ejecutar:"
            print "python eval.py nombreArchivo.txt"
            return
        elif len(sys.argv)==2:
            find_filename = sys.argv[1]
            print "buscar'e en " + find_filename
        else:
            print "Mal llamado, ejecutar con un par'ametro para buscar una regex en un archivo:"
            print "python eval.py nombreArchivo.txt"
            print "o sin par'ametros para aceptar o rechazar una regex:"
            print "python eval.py"
            return

        a = Determinizer(self.automata)
        da = a.determinize()

        da = a.stringuify_set_states(da)
        da.generate_diagram("00-final")

        d = DeterministicAutomata(da)

        f = open(find_filename, 'r')
        ln = 1
        for line in f:
            #print 'Parseando {' + line[:-1] + '}'
            if d.parse(str(line)):
                print 'Match Line '+str(ln)+': ' + str(line),
            else:
            	sys.stderr.write('No acepto la cadena\n')
            ln += 1



    # $ANTLR start "regex"
    # regexs.g:68:1: regex : e '\\n' ;
    def regex(self, ):

        e1 = None


        try:
            try:
                # regexs.g:68:6: ( e '\\n' )
                # regexs.g:68:8: e '\\n'
                pass 
                #action start
                #print "BEGIN"
                #action end
                self._state.following.append(self.FOLLOW_e_in_regex42)
                e1 = self.e()

                self._state.following.pop()
                #action start
                #print "END";
                #action end
                self.match(self.input, 7, self.FOLLOW_7_in_regex45)
                #action start
                self.automata = e1; self.procesar_archivo();
                #action end




            except RecognitionException, re:
                self.reportError(re)
                self.recover(self.input, re)
        finally:

            pass
        return 

    # $ANTLR end "regex"


    # $ANTLR start "a0"
    # regexs.g:70:1: a0 returns [val] : ( '(' e ')' | CARACTER | DOT );
    def a0(self, ):

        val = None

        CARACTER3 = None
        e2 = None


        try:
            try:
                # regexs.g:70:17: ( '(' e ')' | CARACTER | DOT )
                alt1 = 3
                LA1 = self.input.LA(1)
                if LA1 == 8:
                    alt1 = 1
                elif LA1 == CARACTER:
                    alt1 = 2
                elif LA1 == DOT:
                    alt1 = 3
                else:
                    nvae = NoViableAltException("", 1, 0, self.input)

                    raise nvae

                if alt1 == 1:
                    # regexs.g:70:19: '(' e ')'
                    pass 
                    self.match(self.input, 8, self.FOLLOW_8_in_a057)
                    self._state.following.append(self.FOLLOW_e_in_a058)
                    e2 = self.e()

                    self._state.following.pop()
                    self.match(self.input, 9, self.FOLLOW_9_in_a059)
                    #action start
                    val = e2
                    #action end


                elif alt1 == 2:
                    # regexs.g:71:4: CARACTER
                    pass 
                    CARACTER3=self.match(self.input, CARACTER, self.FOLLOW_CARACTER_in_a066)
                    #action start
                    val =  AutomataChar(CARACTER3.text,self.idaut); val.generate_diagram(str(self.idaut)+"-char"); self.idaut+=1;
                    #action end


                elif alt1 == 3:
                    # regexs.g:72:4: DOT
                    pass 
                    self.match(self.input, DOT, self.FOLLOW_DOT_in_a074)
                    #action start
                    val = AutomataDot(self.idaut); val.generate_diagram(str(self.idaut)+"-char"); self.idaut+=1;
                    #action end



            except RecognitionException, re:
                self.reportError(re)
                self.recover(self.input, re)
        finally:

            pass
        return val

    # $ANTLR end "a0"


    # $ANTLR start "a1"
    # regexs.g:74:1: a1 returns [val] : a0 ( OP )* ;
    def a1(self, ):

        val = None

        OP5 = None
        a04 = None


        try:
            try:
                # regexs.g:74:17: ( a0 ( OP )* )
                # regexs.g:75:2: a0 ( OP )*
                pass 
                self._state.following.append(self.FOLLOW_a0_in_a189)
                a04 = self.a0()

                self._state.following.pop()
                #action start
                val =  a04 
                #action end
                # regexs.g:75:24: ( OP )*
                while True: #loop2
                    alt2 = 2
                    LA2_0 = self.input.LA(1)

                    if (LA2_0 == OP) :
                        alt2 = 1


                    if alt2 == 1:
                        # regexs.g:75:25: OP
                        pass 
                        OP5=self.match(self.input, OP, self.FOLLOW_OP_in_a194)
                        #action start
                                                    
                        if OP5.text == '+':
                            val = AutomataMas(val, self.idaut)
                            val.generate_diagram(str(self.idaut)+"-autMas")
                            self.idaut+=2
                        if OP5.text == '?':
                            val = AutomataOptional(val, self.idaut)
                            val.generate_diagram(str(self.idaut)+"-autOptional")
                            self.idaut+=2
                        if OP5.text == '*':
                            val = AutomataStar(val, self.idaut)
                            val.generate_diagram(str(self.idaut)+"-autStar")
                            self.idaut+=2

                        #action end


                    else:
                        break #loop2




            except RecognitionException, re:
                self.reportError(re)
                self.recover(self.input, re)
        finally:

            pass
        return val

    # $ANTLR end "a1"


    # $ANTLR start "a3"
    # regexs.g:90:1: a3 returns [val] : ( a1 )+ ;
    def a3(self, ):

        val = None

        a16 = None


        val = AutomataVacio(self.idaut); val.generate_diagram(str(self.idaut)+"-empty"); self.idaut+=1;
        try:
            try:
                # regexs.g:92:5: ( ( a1 )+ )
                # regexs.g:92:7: ( a1 )+
                pass 
                # regexs.g:92:7: ( a1 )+
                cnt3 = 0
                while True: #loop3
                    alt3 = 2
                    LA3_0 = self.input.LA(1)

                    if ((CARACTER <= LA3_0 <= DOT) or LA3_0 == 8) :
                        alt3 = 1


                    if alt3 == 1:
                        # regexs.g:92:8: a1
                        pass 
                        self._state.following.append(self.FOLLOW_a1_in_a3122)
                        a16 = self.a1()

                        self._state.following.pop()
                        #action start
                        val = AutomataConcat(val, a16, self.idaut); val.generate_diagram(str(self.idaut)+"-concat"); self.idaut+=1;
                        #action end


                    else:
                        if cnt3 >= 1:
                            break #loop3

                        eee = EarlyExitException(3, self.input)
                        raise eee

                    cnt3 += 1
                #action start
                val.generate_diagram(str(self.idaut)+"-concat-final")
                #action end




            except RecognitionException, re:
                self.reportError(re)
                self.recover(self.input, re)
        finally:

            pass
        return val

    # $ANTLR end "a3"


    # $ANTLR start "a4"
    # regexs.g:94:1: a4 returns [val] : s1= a3 ( '|' s2= a3 )* ;
    def a4(self, ):

        val = None

        s1 = None

        s2 = None


        try:
            try:
                # regexs.g:94:16: (s1= a3 ( '|' s2= a3 )* )
                # regexs.g:94:18: s1= a3 ( '|' s2= a3 )*
                pass 
                self._state.following.append(self.FOLLOW_a3_in_a4140)
                s1 = self.a3()

                self._state.following.pop()
                #action start
                val=s1
                #action end
                # regexs.g:94:39: ( '|' s2= a3 )*
                while True: #loop4
                    alt4 = 2
                    LA4_0 = self.input.LA(1)

                    if (LA4_0 == 10) :
                        alt4 = 1


                    if alt4 == 1:
                        # regexs.g:94:40: '|' s2= a3
                        pass 
                        self.match(self.input, 10, self.FOLLOW_10_in_a4145)
                        self._state.following.append(self.FOLLOW_a3_in_a4149)
                        s2 = self.a3()

                        self._state.following.pop()
                        #action start
                        val = AutomataUnion(val, s2, self.idaut); val.generate_diagram(str(self.idaut)+"-union"); self.idaut+=1;
                        #action end


                    else:
                        break #loop4




            except RecognitionException, re:
                self.reportError(re)
                self.recover(self.input, re)
        finally:

            pass
        return val

    # $ANTLR end "a4"


    # $ANTLR start "e"
    # regexs.g:96:1: e returns [val] : a4 ;
    def e(self, ):

        val = None

        a47 = None


        try:
            try:
                # regexs.g:97:5: ( a4 )
                # regexs.g:97:8: a4
                pass 
                self._state.following.append(self.FOLLOW_a4_in_e168)
                a47 = self.a4()

                self._state.following.pop()
                #action start
                val = a47
                #action end




            except RecognitionException, re:
                self.reportError(re)
                self.recover(self.input, re)
        finally:

            pass
        return val

    # $ANTLR end "e"


    # Delegated rules


 

    FOLLOW_e_in_regex42 = frozenset([7])
    FOLLOW_7_in_regex45 = frozenset([1])
    FOLLOW_8_in_a057 = frozenset([4, 5, 8])
    FOLLOW_e_in_a058 = frozenset([9])
    FOLLOW_9_in_a059 = frozenset([1])
    FOLLOW_CARACTER_in_a066 = frozenset([1])
    FOLLOW_DOT_in_a074 = frozenset([1])
    FOLLOW_a0_in_a189 = frozenset([1, 6])
    FOLLOW_OP_in_a194 = frozenset([1, 6])
    FOLLOW_a1_in_a3122 = frozenset([1, 4, 5, 8])
    FOLLOW_a3_in_a4140 = frozenset([1, 10])
    FOLLOW_10_in_a4145 = frozenset([4, 5, 8])
    FOLLOW_a3_in_a4149 = frozenset([1, 10])
    FOLLOW_a4_in_e168 = frozenset([1])



def main(argv, stdin=sys.stdin, stdout=sys.stdout, stderr=sys.stderr):
    from antlr3.main import ParserMain
    main = ParserMain("regexsLexer", regexsParser)
    main.stdin = stdin
    main.stdout = stdout
    main.stderr = stderr
    main.execute(argv)


if __name__ == '__main__':
    main(sys.argv)
